package io.linfeng.api.app.auth.service;

import com.rabbitmq.client.Channel;
import io.linfeng.common.utils.JsonUtil;
import org.springframework.amqp.core.Message;
import io.linfeng.api.app.auth.entity.Mail;
import io.linfeng.common.config.RabbitConfig;
import io.linfeng.common.utils.SendMailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author RJF
 * @date create at 2024-07-2024/7/28-13:38
 * copyright @2024 China Automotive Technology & Research Center Co.Ltd
 */
@Component
@Slf4j
public class ConsumerMailService {

    @Resource
    private SendMailUtil sendMailUtil;

    @RabbitListener(queues = RabbitConfig.MAIL_QUEUE_NAME)
    public void consume(Message message, Channel channel) throws IOException {
        //将消息转化为对象
        String str = new String(message.getBody());
        Mail mail = JsonUtil.strToObj(str, Mail.class);
        log.info("收到消息: {}", mail.toString());

        MessageProperties properties = message.getMessageProperties();
        long tag = properties.getDeliveryTag();

        boolean success = sendMailUtil.send(mail);
        if (success) {
            channel.basicAck(tag, false);// 消费确认
        } else {
            channel.basicNack(tag, false, true);
        }
    }
}

